<template>
  <div class="ma-content-block lg:flex justify-between p-4">
    <!-- CRUD 组件 -->
    <ma-crud :options="options" :columns="columns" ref="crudRef">
      <template #tableBeforeButtons="{ record }">
          <a-button type="primary" @click="handleXinzengs(1,{})"> 新增</a-button>
      </template>
      <template #operationBeforeExtend="{ record }">
          <a-button type="text" size="mini" @click="handleEdits(2,record)"> 编辑</a-button>
      </template>
      <template #contract_id="{record}">
        <div>
          {{ record.contract.name }}
        </div>
      </template>
      <template #weight_type="{record}">
        <div>
          {{ handleweightType(record.weight_type) }}
        </div>
      </template>
      <template #price_type="{record}">
        <div>
          {{ handlepriceType(record.price_type) }}
        </div>
      </template>
      <template #is_checked="{record}">
        <div>
          {{ record.is_checked == 1?'是':'否' }}
        </div>
      </template>
      <template #price_config="{record}">
        <a-popover >
          <a-link>查看详情</a-link>
          <template #content>
            <div v-if="record.price_type == 17 || record.price_type == 20 || record.price_type == 12">
              <div v-for="(item,index) in record.price_config" :key="index">
                <div v-if="item.transport_type == 1 && item.jieti_data[0].price != ''" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">集装箱：</div>
                  <div>
                    <div v-for="(items,indexs) in item.jieti_data" :key="indexs">{{ items.box_size == 1?'20英尺':'40英尺' }}：{{items.range}} {{items.jieti_time == 1?'天':'小时'}} {{items.price + '元'}}/{{handleunit(items.unit)}};</div> 
                  </div>
                </div>
                <div v-if="item.transport_type == 2 && item.jieti_data[0].price != ''" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">整车：</div>
                  <div>
                    <div v-for="(items,indexs) in item.jieti_data" :key="indexs">{{items.range}} {{items.jieti_time == 1?'天':'小时'}} {{items.price + '元'}}/{{handleunit(items.unit)}};</div> 
                  </div>
                </div>
                <div v-if="item.transport_type == 3 && item.jieti_data[0].price != ''" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">批量快运：</div>
                  <div>
                    <div v-for="(items,indexs) in item.jieti_data" :key="indexs">{{items.range}} {{items.jieti_time == 1?'天':'小时'}} {{items.price + '元'}}/{{handleunit(items.unit)}};</div> 
                  </div>
                </div>
              </div>
            </div>
            <div v-else>
              <div v-for="(item,index) in record.price_config" :key="index">
                <div v-if="item.transport_type == 1 && item.is_goods == 1" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">集装箱：</div>
                  <div >按集装箱装卸费率计算;</div> 
                </div>
                <div v-if="item.transport_type == 1 && item.is_goods != 1 && item.box[0].price !=''" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">集装箱：</div>
                  <div >
                    <div v-for="(items,indexs) in item.box" :key="indexs">{{ items.box_size == 1?'20英尺':'40英尺' }}：{{items.price + '元'}}/{{handleunit(items.unit)}};</div> 
                  </div>
                </div>
                <div v-if="item.transport_type == 2 && item.is_goods == 1" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">整车：</div>
                  <div>
                    <div >按品名装卸费率计算;</div> 
                  </div>
                </div>
                <div v-if="item.transport_type == 2 && item.is_goods != 1 && item.price !=''" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">整车：</div>
                  <div>
                    <div >{{item.price + '元'}}/{{handleunit(item.unit)}};</div> 
                  </div>
                </div>
                <div v-if="item.transport_type == 3 && item.is_goods == 1" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">批量快运：</div>
                  <div>
                    <div >按品名装卸费率计算;</div> 
                  </div>
                </div>
                <div v-if="item.transport_type == 3 && item.is_goods != 1 && item.price !=''" class="flex" style="margin-bottom: 12px">
                  <div style="width: 80px;">批量快运：</div>
                  <div>
                    <div >{{item.price + '元'}}/{{handleunit(item.unit)}}； {{ item.limit_weight != ''?`不足 ${item.limit_weight} 吨，按此重量作为最低重量计费`:'' }};</div> 
                  </div>
                </div>
              </div>
            </div>
          </template>
        </a-popover>
        
      </template>
      
      
    </ma-crud>


    <!-- 新增弹窗 -->
    <a-modal :mask-closable="false"  v-model:visible="showXinzeng"  @cancel="showXinzeng =  false" :width="1300" :title="tabType == 1?'新增':'编辑'" :on-before-ok="handleXinZengBefore" >
      <div style="max-height:600px;">
        <div style="display:flex;margin-bottom: 2%;">
          <div>公司名称：</div>
          <a-input  style="flex:1;" v-model="props.inforows.dept.name" placeholder="请输入公司名称" allow-clear :disabled="true" />
        </div>
        <div style="display:flex;margin-bottom: 2%;">
          <div>合同名称：</div>
          <a-input  style="flex:1;" v-model="props.inforows.name" placeholder="请输入合同名称" allow-clear :disabled="true" />
        </div>
        <div style="display:flex;margin-bottom: 2%;">
          <div>费用类型：</div>
          <!-- :disabled="inforow.transport_type == 2?true:false" -->
          <a-select v-model="fromData.price_type" style="flex:1" :filter-option="filterOption"  placeholder="请选择费用类型" @change="handlePriceTypeCharge" allow-search >
            <a-option v-for="item of chargeTypeList" :value="item.key" :label="item.title" :disabled="item.disabled" />
          </a-select>
        </div>
        <div style="display:flex;margin-bottom: 2%;">
          <div>计费名称：</div>
          <a-input  style="flex:1;" v-model="fromData.name" placeholder="请输入计费名称" allow-clear  />
        </div>
        <div style="display:flex;margin-bottom: 2%;">
          <div>计费节点：</div>
          <!-- :disabled="inforow.transport_type == 2?true:false" -->
          <a-select v-model="fromData.billing_node" style="flex:1"  placeholder="请选择计费节点">
            <a-option v-for="item of jifeiArr" :value="item.key" :label="item.title" :disabled='item.disabled' />
          </a-select>
        </div>
        <div style="display:flex;margin-bottom: 2%;" >
          <div>计费规则：</div>
          <costMaster :fromData="fromData" :josnData="josnData" :unitList="unitList" v-if="showXinzeng" @update="handleCostUpdate"></costMaster>
        </div>
        <div style="display:flex;margin-bottom: 2%;">
          <div>计费重量：</div>
          <!-- :disabled="inforow.transport_type == 2?true:false" -->
          <a-radio-group v-model="fromData.weight_type" :options="weightTypeList" >
            <template #label="{ data }">
              <div>{{ data.title }}</div>
            </template>
          </a-radio-group>
        </div>
        <div style="display:flex;margin-bottom: 2%;" >
          <div>计费时间：</div>
          <a-space direction="vertical" size="large">
            <a-radio-group v-model="fromData.time_type" :options="timeTypeArr" />
          </a-space>
        </div>
        <!-- <div style="display:flex;margin-bottom: 2%;">
          <div>是否仓储：</div>
          <a-select v-model="fromData.serve_type" style="flex:1"  placeholder="请选择是否仓储">
            <a-option v-for="item of serveArr" :value="item.key" :label="item.title" />
          </a-select>
        </div> -->
        <div style="display:flex;margin-bottom: 2%;" >
          <div>是否默认勾选账单：</div>
          <a-space direction="vertical" size="large">
            <a-radio-group v-model="fromData.is_checked" :options="checkedTypeArr" />
          </a-space>
        </div>
        
        <div style="display:flex;margin-bottom: 2%;">
          <div style="margin-right:28px">备注：</div>
          <a-textarea v-model="fromData.remark" style="flex:1;" placeholder="请输入备注"  allow-clear/>
        </div>
        <div style="height: 20px;"></div>
      </div>
    </a-modal>
    
  </div>
</template>
<script setup>
import { ref, reactive,defineProps,onMounted } from 'vue'
import systemUserContractCharging from '@/api/system/systemUserContractCharging'
import costMaster from "@/components/costMaster/index.vue";
import { Message } from '@arco-design/web-vue'
import { pinyin } from "pinyin-pro"
import commonApi from "@/api/common";
import { request } from "@/utils/request.js";
import tool from '@/utils/tool'
import * as common from '@/utils/common'
import { before } from 'lodash'
const filterOption = (v,option)=>{
  return option.keywords.some(keywords=>keywords.includes(v))
}
const crudRef = ref()
const tabType = ref()
const showXinzeng = ref(false)
const serveArr = ref([])
const timeTypeArr = ref([
  {label:'入库时间（汽车只能选择入库时间）',value:'1'},
  {label:'卸火车时间',value:'2'},
  {label:'通知时间',value:'3'},
])
const checkedTypeArr = ref([
  {label:'是',value:'1'},
  {label:'否',value:'0'},
])
const jifeiArr = ref([
  
])
const unitList = ref([])
const chargeTypeList = ref([])
const weightTypeList = ref([])
const josnData = ref([])
const fromData = ref({
  name:'',
  weight_type:'',
  price_type:'',
  billing_node:'1',
  time_type:'3',
  is_checked:'1',
  price_config:[],
  remark:''
})
const props = defineProps({
    inforows: {
			default: {},
		},
});
const handleCostUpdate = (e)=>{
  josnData.value = e
}
const handleweightType = (item)=>{
  let name = ''
  weightTypeList.value.map((v,i)=>{
    if(v.key == item){
      name = v.title
    }
  })
  return name
}
const handlepriceType = (item)=>{
  let name = ''
  chargeTypeList.value.map((v,i)=>{
    if(v.key == item){
      name = v.title
    }
  })
  return name
}
const handleunit = (item)=>{
  let name = ''
  unitList.value.map((v,i)=>{
    if(v.id == item){
      name = v.name
    }
  })
  return name
}
const handlePriceTypeCharge = (e)=>{
  if(e == 2 || e == 3 || e == 5 || e == 6 || e == 7 || e == 10 || e == 11 || e == 19){  //   三个 加 非阶段费用
    josnData.value = [
      {
        transport_type: "2",
        price:'',  // 金额
        unit:'',   // 单位
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
        is_jieti:0,
        flag:'',
      },
      {
        transport_type: "1",
        is_jieti:0,
        box: [
          {
            box_size: 1,
            price: '',
            unit: ""
          },
          {
            box_size: 2,
            price: '',
            unit: ""
          }
        ],
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
        flag:''
      },
      {
        transport_type: "3",
        price:'',  // 金额
        unit:'',   // 单位
        limit_weight:'',   // 不足重量
        flag:'',
        is_jieti:0,
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
      },
    ]
  }else if(e == 4 || e == 18){  //  集装箱费用
    josnData.value = [
      {
        transport_type: "1",
        is_jieti:0,
        box: [
          {
            box_size: 1,
            price: '',
            unit: ""
          },
          {
            box_size: 2,
            price: '',
            unit: ""
          }
        ],
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
      }
    ]
  }else if(e == 17){  //  集装箱阶梯费用
    josnData.value = [
      {
        transport_type: "1",
        is_jieti:1,
        jieti_time:1,
        jieti_data: [
          [
            {
              box_size: 1,
              price: '',
              unit: "",
              range:'',
              start:'',
              end:''
            },
          ],
          [
            {
              box_size: 2,
              price: '',
              unit: "",
              range:'',
              start:'',
              end:''
            }
          ]
        ],
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
      }
    ]
  }else if(e == 20 ||  e == 12){  //  货车阶梯费用
    josnData.value = [
      {
        transport_type: "2",
        is_jieti:1,
        jieti_time:1,
        jieti_data: [
            {
              price: '',
              unit: "",
              range:'',
              start:'',
              end:''
            },
        ],
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
      },
      {
        transport_type: "1",
        is_jieti:1,
        jieti_time:1,
        jieti_data: [
          [
            {
              box_size: 1,
              price: '',
              unit: "",
              range:'',
              start:'',
              end:''
            },
          ],
          [
            {
              box_size: 2,
              price: '',
              unit: "",
              range:'',
              start:'',
              end:''
            }
          ]
        ],
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
      },
      {
        transport_type: "3",
        is_jieti:1,
        jieti_time:1,
        jieti_data: [
            {
              price: '',
              unit: "",
              range:'',
              start:'',
              end:''
            },
        ],
        is_goods:0,   // 0 没选择按品名装卸费率计算   1 选择按品名装卸费率计算
      },
    ]
  }

  chargeTypeList.value.map((v,i)=>{
    if(e == v.key){
      fromData.value.name = v.title
    }
  })
}
const handleXinzengs = (type)=>{
  tabType.value = type
  fromData.value = {
    name:'',
    weight_type:'',
    // serve_type : "1",
    price_type:'',
    billing_node:'1',
    time_type:'3',
    price_config:[],
    is_checked:'1',
    remark:''
  }
  showXinzeng.value = true
}
const handleEdits = (type,e)=>{
  tabType.value = type
  fromData.value = {
    name:e.name,
    // serve_type : e.data.serve_type,
    weight_type:e.weight_type + '',
    price_type:e.price_type + '',
    billing_node:e.billing_node + '',
    time_type:e.time_type + '',
    price_config:e.price_config,
    is_checked:e.is_checked + '',
    remark:e.remark,
    id:e.id
  }
  let price_config = JSON.parse(JSON.stringify(e.price_config))
  if(fromData.value.price_type == 17 || fromData.value.price_type == 20 || fromData.value.price_type == 12){
    price_config.map((v,i)=>{
      if(v.transport_type == 1){
        let arr = []
        let arr2 = []
        v.jieti_data.map((vv,ii)=>{
          if(vv.box_size == 1){
            arr.push(vv)
          }
          if(vv.box_size == 2){
            arr2.push(vv)
          }
        })
        v.jieti_data = [arr,arr2]
      }
    })
  }
  josnData.value = price_config
  showXinzeng.value = true
  
}
const handleXinZengBefore = async ()=>{
  if(fromData.value.name == ''){
    Message.error('请输入费用模版名称')
    return false
  }
  if(fromData.value.price_type == ''){
    Message.error('请选择费用类型')
    return false
  }
  if(fromData.value.weight_type == ''){
    Message.error('请选择计费重量')
    return false
  }
  let price_config = JSON.parse(JSON.stringify(josnData.value))
  if(fromData.value.price_type == 17 || fromData.value.price_type == 20 || fromData.value.price_type == 12){
    price_config.map((v,i)=>{
      if(v.transport_type == 1){
        let arr = []
        v.jieti_data.map((vv,ii)=>{
          vv.map((vvv,iii)=>{
            vvv.range = vvv.start +  '-' + vvv.end
            arr.push(vvv)
          })
        })
        v.jieti_data = arr
      }else{
        v.jieti_data.map((vv,ii)=>{
          vv.range = vv.start +  '-' + vv.end
        })
      }
    })
  }
  if(tabType.value == 1){
    let res = await systemUserContractCharging.save({
      dept_id:props.inforows.dept_id,
      contract_id:props.inforows.id,
      billing_node:fromData.value.billing_node,
      name:fromData.value.name,
      // serve_type:fromData.value.serve_type,
      remark:fromData.value.remark,
      time_type:fromData.value.time_type,
      price_type:fromData.value.price_type,
      weight_type:fromData.value.weight_type,
      price_config:price_config,
      is_checked:fromData.value.is_checked
    })
    if(res.code == 200){
      Message.success('新增成功')
        crudRef.value.refresh()
        return true
    }else{
      Message.error(res.message)
      return false
    }
    
  }else{
    let res = await systemUserContractCharging.update(fromData.value.id,{
      dept_id:props.inforows.dept_id,
      contract_id:props.inforows.id,
      billing_node:fromData.value.billing_node,
      name:fromData.value.name,
      // serve_type:fromData.value.serve_type,
      remark:fromData.value.remark,
      time_type:fromData.value.time_type,
      price_type:fromData.value.price_type,
      weight_type:fromData.value.weight_type,
      price_config:price_config,
      is_checked:fromData.value.is_checked
    })
    if(res.code == 200){
      Message.success('编辑成功')
      crudRef.value.refresh()
      return true
    }else{
      Message.error(res.message)
      return false
    }
  }
}

onMounted(() => {
  commonApi.getDict("weight_type").then((res) => {
    let _data = res.data;
    _data.map((v,i)=>{
      v.value = v.key
    })
    weightTypeList.value = _data
  });
  commonApi.getDict("price_type").then((res) => {
    let _data =  res.data
    _data.map((v,i)=>{
      if(v.key == 1 || v.key == 8 || v.key == 9 || v.key == 13 || v.key == 14 || v.key == 15 || v.key == 16 || v.key == 21 || v.key == 22){
        v.disabled = true
      }else{
        v.disabled = false
      }
    })
    res.data.map((v,i)=>{
        v.keywords = [
          v.title,
          pinyin(v.title,{toneType:'none',pattern:'first'}).split(' ').join(''),
          pinyin(v.title,{toneType:'none',pattern:'first'}).split(' ').join('').toUpperCase()
        ]
    })
    chargeTypeList.value = res.data;
  });
  commonApi.getDict("billing_node").then((res) => {
    jifeiArr.value = res.data;
  });
  // commonApi.getDict("serve_type").then((res) => {
  //   serveArr.value = res.data;
  // });
  request({
      url:'financial/unit/index',
      method: 'get',
      params:{
        openPage:false
      },
    }).then(res=>{
      unitList.value = res.data.items
    })
  
  crudRef.value.requestData()
});


const options = reactive({
  id: 'flyos_system_user_contract_charging',
  rowSelection: {
    showCheckedAll: true
  },
  pk: 'id',
  operationColumn: true,
  autoRequest:false,
  operationWidth: 160,
  formOption: {
    viewType: 'modal',
    width: 600
  },
  api: systemUserContractCharging.getList,
  recycleApi: systemUserContractCharging.getRecycleList,
  add: {
    show: false,
    api: systemUserContractCharging.save,
    auth: ['system:userContractCharging:save']
  },
  edit: {
    show: false,
    api: systemUserContractCharging.update,
    auth: ['system:userContractCharging:update']
  },
  delete: {
    show: true,
    topshow:true,
    api: systemUserContractCharging.deletes,
    auth: ['system:userContractCharging:delete'],
    realApi: systemUserContractCharging.realDeletes,
    realAuth: ['system:userContractCharging:realDeletes']
  },
  recovery: {
    show: false,
    api: systemUserContractCharging.recoverys,
    auth: ['system:userContractCharging:recovery']
  },
  import: {
    show: false,
    url: 'system/userContractCharging/import',
    templateUrl: 'system/userContractCharging/downloadTemplate',
    auth: ['system:userContractCharging:import']
  },
  export: {
    show: false,
    url: 'system/userContractCharging/export',
    auth: ['system:userContractCharging:export']
  },
  beforeRequest:(params)=>{
    console.log(props.inforows)
    params.contract_id = props.inforows.id
  }
})

const columns = reactive([
  {
    title: "ID",
    dataIndex: "id",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    commonRules: {
      required: true,
      message: "请输入ID"
    }
  },
  // {
  //     title: '合同公司',
  //     dataIndex: 'dept_id',
  //     common:true,
  //     addDefaultValue:async function (){
  //         return inforow.value.dept_id;
  //     },
  //     search: false,
  //     disabled:true,
  //     control: (val) => {
  //                 if (inforow.value.is_taoxiang == 0) {
  //                     return {
  //                         is_taoxiang: { display: false },
  //                     }
  //                 }
  //                 if (inforow.value.is_taoxiang == 1) {
  //                     return {
  //                         is_taoxiang: { display: true },
  //                     }
  //                 }
  //             }
  //   },
  //   {
  //     title: '合同名称',
  //     dataIndex: 'contract_id', 
  //     align: "center",
  //     search: false,
  //     addDefaultValue:async function (){
  //         return inforow.value.id;
  //     },
  //     common: true,
  //   },
  {
    title: "计费名称",
    dataIndex: "name",
    formType: "input",
    search: true
  },
  {
    title: "费用类型",
    dataIndex: "price_type",
    formType: "input",
    search: false
  },
  {
    title: "价格配置",
    dataIndex: "price_config",
    formType: "input",
  },
  {
    title: "计费节点",
    dataIndex: "billing_node",
    formType: "select",
    search: false,
    dict: {
              name: "billing_node",
              props: {
                  label: "title",
                  value: "key",
              },
              translation: true,
          },
      commonRules: {
        required: true,
        message: "请选择计费节点"
      }
  },
  {
    title: "计费备注",
    dataIndex: "remark",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "计费时间",
    dataIndex: "time_type",
    formType: "select",
    search: false,
    dict: {
      data: [
        {
          label: "入库时间（汽车只能选择入库时间）",
          value: "1"
        },
        {
          label: "卸火车时间",
          value: "2"
        },
        {
          label: "通知时间",
          value: "3"
        }
      ],
      translation: true
    }
  },
  {
    title: "参与计算重量",
    dataIndex: "weight_type",
    formType: "input",
    search: false
  },
  
  // {
  //   title: "服务类型",
  //   dataIndex: "serve_type",
  //   formType: "select",
  //   align: "center",
  //   dict: {
	// 		name: "serve_type",
	// 		props: {
	// 			label: "title",
	// 			value: "key",
	// 		},
	// 		translation: true,
	// 	},
  //   commonRules: {
  //     required: true,
  //     message: "请选择服务类型"
  //   }
  // },
  {
    title: "是否默认勾选账单",
    dataIndex: "is_checked",
    formType: "input",
    search: false
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "更新时间",
    dataIndex: "updated_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "删除时间",
    dataIndex: "deleted_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "创建者",
    dataIndex: "created_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "更新者",
    dataIndex: "updated_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  }
])
</script>
<script> export default { name: 'system:userContractCharging' } </script>